#region Using

using System;
using System.IO;
using System.Web;
using System.Net;
using System.ComponentModel;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Xml;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using BlogEngine.Core;

#endregion


namespace Controls
{
    /// <summary>
    /// Creates and displays a slideshow.
    /// </summary>
    public class RandomPhoto : WebControl
    {
        private DisplayPhoto _Photo = new DisplayPhoto();

        private int _Size = 0;
        [BindableAttribute(true)]
        [CategoryAttribute("Appearance")]
        public int Size
        {
            get { return _Size; }
            set { _Size = value; }
        }

        private bool _Inline;
        [BindableAttribute(true)]
        [CategoryAttribute("Appearance")]
        public bool Inline
        {
            get { return _Inline; }
            set { _Inline = value; }
        }

        /// <summary>
        /// Standard Constructor.  Adds a photo control to this control collection to ensure OnPreRender is fired.
        /// </summary>
        public RandomPhoto() :base()
        {
            this.Controls.Add(_Photo);
        }

        /// <summary>
        /// use the photo object to render a standard photo image
        /// </summary>
        /// <param name="writer"></param>
        protected override void Render(HtmlTextWriter writer)
        {
            using (System.IO.StringWriter sw = new System.IO.StringWriter())
            {
                _Photo.PhotoId = GetRandomPhoto();
                _Photo.Slug = string.Empty;
                _Photo.Size = _Size;
                _Photo.Inline = _Inline;
                _Photo.CssClass = this.CssClass;
                _Photo.RenderControl(new HtmlTextWriter(sw));
                writer.Write(sw.ToString());
            }
        }

        /// <summary>
        /// Tries three times to get a random visible image
        /// </summary>
        /// <returns></returns>
        private Guid GetRandomPhoto()
        {
            int tries = 0;
            int photoIndex = -1;
            Random random = new Random();

            //get a random photo - try three times only and only if there are photos
            if (Photo.Items.Count > 0)
            {
                while (photoIndex == -1 && tries < 4)
                {
                    photoIndex = random.Next(0, Photo.Items.Count - 1);
                    if (!Photo.Items[photoIndex].IsVisible)
                    {
                        photoIndex = -1;
                        tries++;
                    }
                }
            }

            return photoIndex == -1 ? Guid.Empty : Photo.Items[photoIndex].Id;
        }
    }
}